<template>
  <div>
    <!-- 面包屑导航区域 -->
    <breadcrumb :breadcrumbs="breadcrumbs" />

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜素与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getAllUsers"
            @change="getAllUsers"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getAllUsers"></el-button>
            </template>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表展示区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserClick(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoleClick(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 7, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUesrClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible="editDialogVisible"
      @close="editDialogClosed"
      width="50%"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="editname">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUesrClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfoClick">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";
import {
  getUsers,
  updateUserStatus,
  addUesr,
  getUserById,
  editUserById,
  deleteUserById,
  setRole,
} from "@/network/Users/users";
import { getRoles } from "@/network/power/roles";

export default {
  name: "Users",
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/; //邮箱正则
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    //验证手机的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3|4|5|8][0-9]\d{4,8}$/; //验证手机
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };

    return {
      breadcrumbs: ["用户管理", "用户列表"],

      queryInfo: {
        query: "",
        pagenum: 1, //页数
        pagesize: 3, //每页多少
      },

      userList: [],
      total: 0,
      addDialogVisible: false, //控制添加用户对话框的显示与隐藏
      addForm: { username: "", password: "", email: "", mobile: "" }, //添加用户表单

      // //添加表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editDialogVisible: false, //控制修改用户对话框的显示与隐藏
      editForm: {}, //查询到的用户信息
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      setRoleDialogVisible: false,
      userInfo: [], //所操作的用户信息
      rolesList: [], //角色信息
      selectRoleId: "",
    };
  },
  components: {
    Breadcrumb,
  },
  methods: {
    /* 网络方法 获取用户列表*/
    getAllUsers() {
      getUsers(this.queryInfo)
        .then((res) => {
          if (res.meta.status != 200)
            return this.$message.error("获取用户列表失败！" + res.meta.msg);
          this.$message.success("获取用户列表成功！");
          this.userList = res.data.users;
          this.total = res.data.total;
        })
        .catch((error) => {
          this.$message.error("获取用户列表失败！" + error);
        });
    },

    // 监听pagesize更改的事件
    handleSizeChange(newPageSize) {
      this.queryInfo.pagesize = newPageSize;
      this.getAllUsers();
    },

    //监听页面值更改的事件
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum;
      this.getAllUsers();
    },

    // 使用el-switch的回调函数change来更改用户状态
    userStatusChanged(userInfo) {
      updateUserStatus(userInfo.id, userInfo.mg_state)
        .then((res) => {
          if (res.meta.status != 200) {
            userInfo.mg_state = !userInfo.mg_state;
            return this.$message.error(`设置状态失败！` + res.meta.msg);
          }

          this.$message.success(`设置 ${userInfo.username} 的状态成功！`);
        })
        .catch((error) => {
          userInfo.mg_state = !userInfo.mg_state;
          this.$message.error("设置状态失败！" + error);
        });
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields(); //清空历史表单数据
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields(); //清空历史表单数据
    },
    //添加用户
    addUesrClick() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;

        addUesr(this.addForm).then((res) => {
          if (res.meta.status != 201)
            return this.$message.error(`添加用户失败！` + res.meta.msg);
          this.$message.success("添加成功！");
          this.addDialogVisible = false;
          this.getAllUsers();
        });
      });
    },

    //展示编辑用户对话框
    showEditDialog(id) {
      0;
      //获取用户信息
      getUserById(id).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取用户信息失败！" + res.meta.msg);
        this.editForm = res.data;
      });
      this.editDialogVisible = true;
    },

    // 修改用户信息
    editUesrClick() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;

        //发起请求提交修改
        editUserById(this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        })
          .then((res) => {
            if (res.meta.status != 200)
              return this.$message.error(`修改用户失败！` + res.meta.msg);
            this.$message.success("修改成功！");
            this.editDialogVisible = false;
            this.getAllUsers();
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },

    // 根据id删除用户信息
    removeUserClick(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUserById(id).then((res) => {
            if (res.meta.status != 200)
              return this.$message.error("删除失败！" + res.meta.msg);
            this.$message.success("删除成功");

            if (this.userList.length === 1) {
              this.queryInfo.pagenum--;
            }
            this.getAllUsers();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除！");
        });
    },
    //展示分配角色的对话框
    setRoleClick(userInfo) {
      this.userInfo = userInfo;
      //获取角色
      getRoles().then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取角色列表失败" + res.meta.msg);
        this.rolesList = res.data;
      });
      this.setRoleDialogVisible = true;
    },

    //分配角色
    saveRoleInfoClick() {
      if (!this.selectRoleId)
        return this.$message.error("请选择要分配的角色！");
      setRole(this.userInfo.id, this.selectRoleId).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("分配角色失败！" + res.meta.msg);
        this.$message.success("分配角色成功");
      });

      setTimeout(() => {
        this.getAllUsers();
      }, 1000);
      this.setRoleDialogVisible = false;
    },
    setRoleDialogClosed() {
      this.selectRoleId = "";
      this.userInfo = {};
    },
  },
  /**生命周期函数 */
  created() {
    this.getAllUsers();
  },
};
</script>

<style lang="less" scoped>
</style>